﻿using System;
using System.Web.Mvc;
using Chatu.ControlLider.Web.Models.Security;

namespace Chatu.ControlLider.Web.Controllers
{
    public partial class AccountController : Controller
    {
        private readonly IFormsAuthentication _formsAuth;
        private readonly IMembershipService _membership;

        public AccountController()
            : this(new FormsAuthenticationService(), new AccountMembershipService())
        { }

        public AccountController(IFormsAuthentication formsAuth, IMembershipService membership)
        {
            _formsAuth = formsAuth;
            _membership = membership;
        }

        public virtual ActionResult LogOn()
        {
#if(DEBUG)
            string userName = System.Configuration.ConfigurationManager.AppSettings["DebugUserName"];
            string password = System.Configuration.ConfigurationManager.AppSettings["DebugUserPassword"] ?? "";

            if (userName != null && _membership.ValidateUser(userName, password))
            {
                _formsAuth.SignIn(userName);
                return RedirectToAction(MVC.Home.Index());
            }
#endif
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
            Justification = "Needs to take same parameter type as Controller.Redirect()")]
        public virtual ActionResult LogOn(string userName, string password, string returnUrl)
        {
            if (!ValidateLogOn(userName, password))
            {
                return View();
            }

            _formsAuth.SignIn(userName);

            if (!string.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }

            return RedirectToAction(MVC.Home.Index());
        }

        public virtual ActionResult LogOff()
        {
            _formsAuth.SignOut();

            return RedirectToAction(MVC.Home.Index());
        }

        [Authorize]
        public virtual ActionResult ChangePassword()
        {
            return View();
        }

        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
            Justification = "Exceptions result in password not being changed.")]
        public virtual ActionResult ChangePassword(string currentPassword, string newPassword, string confirmPassword)
        {
            if (!ValidateChangePassword(currentPassword, newPassword, confirmPassword))
            {
                return View();
            }

            try
            {
                if (_membership.ChangePassword(User.Identity.Name, currentPassword, newPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }

                ModelState.AddModelError("_FORM", "La clave actual es incorrecta o la nueva clave no es valida.");
                
                return View();
            }
            catch
            {
                ModelState.AddModelError("_FORM", "La clave actual es incorrecta o la nueva clave no es valida.");
                
                return View();
            }
        }

        public virtual ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        #region Private Helper Methods

        private bool ValidateChangePassword(string currentPassword, string newPassword, string confirmPassword)
        {
            if (String.IsNullOrEmpty(currentPassword))
            {
                ModelState.AddModelError("currentPassword", "Clave actual es requerida.");
            }

            if (newPassword == null || newPassword.Length < _membership.MinPasswordLength)
                ModelState.AddModelError("newPassword", string.Format("Su clave tiene que tener {0} o mas caracteres.",_membership.MinPasswordLength));

            if (!String.Equals(newPassword, confirmPassword, StringComparison.Ordinal))
                ModelState.AddModelError("_FORM", "La nueva clave y la confirmación de la clave no coinciden.");

            return ModelState.IsValid;
        }

        private bool ValidateLogOn(string userName, string password)
        {
            if (String.IsNullOrEmpty(userName))
            {
                ModelState.AddModelError("username", "Login es requerido.");
            }
            if (String.IsNullOrEmpty(password))
            {
                ModelState.AddModelError("password", "Clave es requerida.");
            }
            if (!_membership.ValidateUser(userName, password))
            {
                ModelState.AddModelError("_FORM", "El login o clave proporsionados son incorrectos.");
            }

            return ModelState.IsValid;
        }

        #endregion
    }
}